#!/usr/bin/env python3
"""
Detailed调试stdio固件
"""

import socket
import subprocess
import time
import struct

print("=== Detailed调试stdio固件 ===\n")

# 启动QEMU
print("1. 启动QEMU with GDB...")
qemu = subprocess.Popen([
    'qemu-system-arm',
    '-M', 'netduinoplus2',
    '-nographic',
    '-kernel', 'build/hello.elf',
    '-gdb', 'tcp::1234',
    '-S',  # 暂停
    '-serial', 'stdio'
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

time.sleep(1)

# 连接GDB
print("2. 连接GDB...")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 1234))

def gdb_cmd(cmd):
    checksum = sum(ord(c) for c in cmd) & 0xFF
    packet = f"${cmd}#{checksum:02x}"
    sock.sendall(packet.encode())
    time.sleep(0.05)
    response = sock.recv(4096)
    return response.decode('latin1', errors='ignore')

print("\n3. CheckPC...")
resp = gdb_cmd('g')  # Read寄存器
print(f"寄存器: {resp[:100]}")

print("\n4. ReadVector表...")
resp = gdb_cmd('m08000000,20')
print(f"Vector表: {resp}")

print("\n5. 单步Execute5步...")
gdb_cmd('c')  # continue
time.sleep(0.1)

for i in range(5):
    sock.sendall(b'\x03')  # interrupt
    time.sleep(0.1)
    pc_resp = gdb_cmd('p/x $pc')
    print(f"  Step {i+1} PC: {pc_resp}")
    gdb_cmd('s')  # step
    time.sleep(0.1)

print("\n6. TrySettings断点Inprintf...")
# Require找Toprintf的地址
resp = gdb_cmd('info symbol printf')
print(f"printf位置: {resp}")

print("\n7. Continue一段时间...")
gdb_cmd('c')
time.sleep(2)

sock.sendall(b'\x03')  # interrupt
time.sleep(0.1)

pc_resp = gdb_cmd('p/x $pc')
print(f"CurrentPC: {pc_resp}")

# CheckYesNoInmain中
resp = gdb_cmd('m08000000,1000')  # Read代码段
if 'Hello' in str(resp):
    print("[OK] 发现'Hello'StringInflash中")

print("\n8. CheckUART寄存器...")
# USART2 DR: 0x40004400
resp = gdb_cmd('m40004400,20')
print(f"USART2寄存器: {resp}")

sock.close()
qemu.terminate()
qemu.wait()

print("\nCompleted")
